package admin

import (
	"SlowAdmin/controllers"
	"SlowAdmin/models"
	"SlowAdmin/pkg/utils"
	"fmt"
	"github.com/astaxie/beego"
	"math/rand"
	"os"
	"path"
	"time"
)

var fileModel models.File

// @title 文件控制器
type FileController struct {
	controllers.BaseController
}

var baseDir = "storage/upload/"

func (c *FileController) Upload() {
	fileType := c.Ctx.Request.PostFormValue("fileType")
	f, h, err := c.GetFile("file")
	ext := path.Ext(h.Filename)
	fmt.Println(h.Header)

	if err != nil {
		c.Fail(err.Error(), nil)
		return
	}

	if !CheckFileType(fileType, ext) {
		c.Fail("对不起, 不支持上传此类型文件", nil)
		return
	}

	date := time.Now().Format("20060102")
	dir := baseDir + fileType + "/" + date + "/"

	dirExists, _ := utils.PathExists(dir)
	if !dirExists {
		err := os.MkdirAll(dir, os.ModePerm)
		if err != nil {
			c.Fail(err.Error(), nil)
			return
		}
	}

	fileName := GenerateRandFileName(ext)

	file := fileModel

	file.Storage = "local"
	file.Domain = beego.AppConfig.String("app_url")
	file.FileName = h.Filename
	file.FileType = fileModel.GetFileType(fileType)
	file.FilePath = dir + fileName
	file.FileSize = int(h.Size)
	file.FileExt = ext

	err = c.SaveToFile("file", file.FilePath)
	f.Close()

	if err != nil {
		c.Fail(err.Error(), nil)
		return
	}

	err = file.Store()

	if err != nil {
		c.Fail(err.Error(), nil)
		return
	}

	c.Success("上传成功", nil)
}

// @title 生成随机文件名
func GenerateRandFileName(ext string) string {
	b := make([]byte, 16)
	rand.Read(b)
	uuid := fmt.Sprintf("%x-%x-%x-%x-%x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:])

	randNumStr := fmt.Sprintf("%d", uuid) + time.Now().Format("20060102150405")

	return utils.Md5(randNumStr) + ext
}

// @title 检查文件类型
func CheckFileType(fileType, ext string) bool {
	pass := make(map[string]bool)
	switch fileType {
	case "image":
		pass[".jpg"] = true
		pass[".jpeg"] = true
		pass[".png"] = true
		pass[".gif"] = true
		pass[".bmp"] = true
	case "video":
		pass[".mp4"] = true
		pass[".avi"] = true
		pass[".rmvb"] = true
		pass[".wmv"] = true
		pass[".mkv"] = true
		pass[".flv"] = true
		pass[".swf"] = true
	case "annex":
		return true
	}

	if _, ok := pass[ext]; ok {
		return true
	}
	return false
}

func (c *FileController) List() {
	page, _ := c.GetInt("page", 1)
	pageSize, _ := c.GetInt("page_size", 15)
	fileType := c.GetString("file_type")
	keyword := c.GetString("keyword", "")

	list, total := fileModel.GetList(page, pageSize, fileType, keyword)

	c.Success("ok", controllers.Result{
		"list":      list,
		"total":     total,
		"page":      page,
		"page_size": pageSize,
	})
}
